import { store } from '../index'
import { defineStore } from 'pinia'
import { getAccessToken, removeToken } from '@/utils/auth'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { getInfo, loginOut } from '@/api/login'
import { getUserProfile } from '@/api/system/user/profile'

const { wsCache } = useCache()

interface UserVO {
  id: number
  avatar: string
  nickname: string
}
interface UserInfoVO {
  permissions: string[]
  roles: string[]
  isSetUser: boolean
  user: UserVO
  profile: any
}

export const useUserStore = defineStore('admin-user', {
  state: (): UserInfoVO => ({
    permissions: [],
    roles: [],
    isSetUser: false,
    user: {
      id: 0,
      avatar: '',
      nickname: ''
    },
    profile: ''
  }),
  getters: {
    getPermissions(): string[] {
      return this.permissions
    },
    getRoles(): string[] {
      return this.roles
    },
    getIsSetUser(): boolean {
      return this.isSetUser
    },
    getUser(): UserVO {
      return this.user
    },
    getProfile(): any {
      return this.profile
    }
  },
  actions: {
    async setUserInfoAction() {
      if (!getAccessToken()) {
        this.resetState()
        return null
      }
      try  {
        const userInfo = await getInfo()
        this.permissions = userInfo.permissions
        this.roles = userInfo.roles
        this.user = userInfo.user
        this.isSetUser = true
        this.profile = userInfo.user.avatar

        wsCache.set(CACHE_KEY.USER, userInfo)
        wsCache.set(CACHE_KEY.ROLE_ROUTERS, userInfo.menus)
      } catch (e) {
        console.log(e)
      }
    },
    async loginOut() {
      await loginOut()
      removeToken()
      const LoginForm = wsCache.get('LOGINFORM')
      wsCache.clear()
      wsCache.set('LOGINFORM', LoginForm, { exp: 30 * 24 * 60 * 60 })
      this.resetState()
    },
    resetState() {
      this.permissions = []
      this.roles = []
      this.isSetUser = false
      this.user = {
        id: 0,
        avatar: '',
        nickname: ''
      }
    },
    async setProfile() {
      const users = await getUserProfile()
      this.profile = users.avatar
    }
  }
})

export const useUserStoreWithOut = () => {
  return useUserStore(store)
}
